<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>最佳拍档</title>
    <meta name="keywords" content="最佳拍档">
    <meta name="description" content="最佳拍档">
    <style>
        .right h2{
            margin: 10px 0;
        }
        .right li{
            margin-bottom: 10px;
        }
        .layui-form-label{
            width: 130px;
        }
        .layui-input-block {
            margin-left: 160px;
        }
    </style>
</head>
<body>
<div class="right p20" style="margin-left: 200px;">
<!--    <div th:include="common/UserHeadDesc :: user_head_desc"></div>-->
    <fieldset class="layui-elem-field layui-field-title">
        <legend>品牌详情</legend>
    </fieldset>
    <form class="layui-form" lay-filter="BrandDetailForm">
        <div class="layui-form-item">
            <label class="layui-form-label">平台ID</label>
            <div class="layui-input-block">
                <input type="text" name="openeaId" autocomplete="off" class="layui-input" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">公司名</label>
            <div class="layui-input-block">
                <input type="text" name="company" autocomplete="off" class="layui-input" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">类品</label>
            <div class="layui-input-block">
                <input type="text" name="category" autocomplete="off" class="layui-input" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">品牌</label>
            <div class="layui-input-block">
                <input type="text" name="brand" autocomplete="off" class="layui-input" readonly>
            </div>
        </div>
    </form>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
        <legend>请完善以下信息方可提交授权申请</legend>
    </fieldset>
    <form class="layui-form" lay-filter="Authorization" id="auth_form_id">
        <div class="layui-form-item">
            <label class="layui-form-label">1688店铺名称</label>
            <div class="layui-input-block">
                <input type="text" name="shopName" placeholder="请填写1688店铺名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">1688一键铺货</label>
            <div class="layui-input-inline">
                <input type="radio" name="oneClickDelivery" value="1" title="是" checked>
                <input type="radio" name="oneClickDelivery" value="0" title="否">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">1688分账功能</label>
            <div class="layui-input-inline">
                <input type="radio" name="splitAccounts" value="1" title="有" checked>
                <input type="radio" name="splitAccounts" value="0" title="无">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">淘宝分销</label>
            <div class="layui-input-inline">
                <input type="radio" name="taobaoDistribution" value="1" title="可以" checked>
                <input type="radio" name="taobaoDistribution" value="0" title="不可以">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">社群分销</label>
            <div class="layui-input-inline">
                <input type="radio" name="communityDistribution" value="1" title="可以" checked>
                <input type="radio" name="communityDistribution" value="0" title="不可以">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">其他分销渠道</label>
            <div class="layui-input-block">
                <input type="text" name="otherDistribution" placeholder="请填写其他分销渠道" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">签约日期</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" name="startDate" placeholder="请选择签约日期" id="startDateid" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">截止日期</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" name="dueDate" placeholder="请选择截止日期" id="dueDateid" readonly>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">授权书附件</label>
            <div class="layui-input-block">
                <div id="attachment_content" style="padding-top: 9px;padding-bottom: 10px;"></div>
                <input id="fileSelector" type="file">
            </div>
        </div>
        <!-- 客户跟进记录时间轴 -->
        <div style="padding-left: 120px;">
            <ul class="layui-timeline" id="logDataTimeLine"></ul>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">客户跟进记录</label>
            <div class="layui-input-block">
                <textarea name="logData" id="logData" placeholder="请填写客户跟进记录" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" id="EditFormBtn" onclick="editAuthForm()">编辑</button>
                <button class="layui-btn" id="SubmitBtn" lay-submit lay-filter="submitAuthForm" style="display: none;">保存</button>
            </div>
        </div>
    </form>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
        <legend> 请完善签约的商品信息</legend>
    </fieldset>
    <div class="layui-row">
        <div class="layui-col-md12" style="padding-right: 20px">
            <table class="layui-table layui-form" lay-filter="EditListTable" id="EditListTable" lay-data="{id: 'tableid'}">
                <thead>
                <tr class="id36567">
                    <th lay-data="{checkbox:true}"></th>
                    <th lay-data="{field:'commodityName', align: 'center'}">商品名称</th>
                    <th lay-data="{field:'commodityMap', align: 'center', templet: '#imgTemp', style: 'height:90px;'}">商品图</th>
                    <th lay-data="{field:'commodityLink', align: 'center'}">商品链接</th>
                    <th lay-data="{field:'specification', align: 'center'}">规格</th>
                    <th lay-data="{field:'supplyPrice', align: 'center'}">供货价（元）</th>
                    <th lay-data="{field:'floorPrice', align: 'center'}">控价</th>
                    <th lay-data="{field:'fare', align: 'center'}">运费</th>
                    <th lay-data="{field:'remark', align: 'center'}">备注</th>
                </tr>
                </thead>
            </table>
        </div>
    </div>
    <!-- 头部工具栏 -->
    <script type="text/html" id="toolbar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon">&#xe624;</i>添加</button>
            <button class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon">&#xe642;</i>修改</button>
            <button class="layui-btn layui-btn-sm" lay-event="delete"><i class="layui-icon">&#xe67e;</i>删除</button>
        </div>
    </script>
    <script type="text/html" id="imgTemp">
        <img src="{{d.commodityMap}}" style="width: 100px;height: 80px;" />
    </script>
</div>

<!--添加商品信息弹窗内容-->
<div id="add_shop_model" style="display: none;">
    <form class="layui-form" lay-filter="addShopForm" id="add_shop_form" style="padding-right: 50px;padding-top: 40px;">
        <div class="layui-form-item">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-block">
                <input type="text" name="commodityName" autocomplete="off" class="layui-input" placeholder="请填写商品名称">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品图</label>
            <div class="layui-input-block">
                <input id="imgSelector" type="file">
            </div>
            <div class="layui-input-block">
                <input type="text" name="commodityMap" placeholder="或填写商品图链接" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品链接</label>
            <div class="layui-input-block">
                <input type="text" name="commodityLink" placeholder="请填写商品链接" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">规格</label>
            <div class="layui-input-block">
                <input type="text" name="specification" placeholder="请填写规格" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">供货价（元）</label>
            <div class="layui-input-block">
                <input type="text" name="supplyPrice" placeholder="请填写与品牌方协商的价格" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">控价</label>
            <div class="layui-input-block">
                <input type="text" name="floorPrice" placeholder="品牌方如有最低价要求，必须填上" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">一件代发</label>
            <div class="layui-input-inline">
                <input type="radio" name="dropShipping" value="1" title="是" checked>
                <input type="radio" name="dropShipping" value="0" title="否">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">运费</label>
            <div class="layui-input-block">
                <textarea name="fare" id="fare" placeholder="包邮填写“包邮”，不包邮填写具体运费标准，注意偏远地区" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" id="remark" placeholder="请填写备注" class="layui-textarea"></textarea>
            </div>
        </div>
    </form>
</div>

</body>
<script src="https://unpkg.com/cos-js-sdk-v5/dist/cos-js-sdk-v5.min.js"></script>
<script type="text/javascript">
    let cos = new COS({
        SecretId: 'AKIDfATcXDdpmW3LOCl48xWptjKflcDZgYAY',
        SecretKey: 'B6mDOK1TggSzGI4buynMgkY8SXMvFK9j',
    });
    let Bucket = 'dev-1308272144'
    let Region = 'ap-guangzhou'
    let folderName = "cms"
    let customerId = "";
    let files = [];
    let attachments = [];
    let logDataJson = [];

    window.onload = function(){
        customerId = GetQueryString("unid")
        if(isNotNull(customerId)){
            initFormData()
            //固定导航栏
            $('a[href="/Admin/WorkRecord"]').parent().addClass('layui-this');
            $('a[href="/Admin/WorkRecord"]').parent().parent().parent().addClass('layui-nav-itemed');
        }else{
            history.go(-1);
        }
    }

    //初始化数据
    function initFormData(){
        initPlatformInfo();
        initAuthorization();
    }

    //初始化平台信息
    function initPlatformInfo() {
        $.ajax({
            url: '/customer/'+customerId,
            type: 'get',
            data: {},
            dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系！！！
            success: function (res) {
                layui.use('form', function(){
                    let form = layui.form;
                    //给表单赋值
                    form.val("BrandDetailForm", {
                        "openeaId": res.data.customer.openeaId
                        ,"company": res.data.customer.company
                        ,"category": res.data.customer.category
                        ,"brand": res.data.customer.brand
                    });
                });
                //提交需要用到原始数据
                logDataJson = res.data.logData
                //给客户跟进记录赋值
                $.each(res.data.logData,function(i,item){
                    if(item.edit){
                        $("#logData").val(item.content)
                    }else{
                        $("#logDataTimeLine").append(
                            '<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis">&#xe63f;</i><div class="layui-timeline-content layui-text"><h3 class="layui-timeline-title">'+item.createTime+'</h3><p>'+item.content+'</p></div></li>'
                        );
                    }
                });
            }
        });
    }

    //初始化授权申请信息
    function initAuthorization(){
        $.ajax({
            url: '/supplement/'+customerId,
            type: 'get',
            data: {},
            dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系！！！
            success: function (res) {
                if(res.data){
                    layui.use('form', function(){
                        let form = layui.form;
                        //给表单赋值
                        form.val("Authorization", {
                            "shopName": res.data.shopName
                            ,"oneClickDelivery": res.data.oneClickDelivery
                            ,"splitAccounts": res.data.splitAccounts
                            ,"taobaoDistribution": res.data.taobaoDistribution
                            ,"communityDistribution": res.data.communityDistribution
                            ,"otherDistribution": res.data.otherDistribution
                            ,"startDate": res.data.startDate
                            ,"dueDate": res.data.dueDate
                        });
                    });
                    //初始化附件
                    let attachs = res.data.attachment;
                    if(isNotNull(attachs)){
                        attachments = attachs.split(",");
                        randerAttachList(0)
                    }
                    $("#fileSelector").attr("hidden","hidden");
                    $("#auth_form_id *").attr("disabled","disabled");
                    $("#EditFormBtn").removeAttr('disabled');
                }else{
                    $("#EditFormBtn").hide();
                    $("#SubmitBtn").show();
                }
            }
        });
    }

    layui.use(['table', 'layer', 'form'], function () {//layui 模块引用，根据需要自行修改
        let layer = layui.layer, table = layui.table, form = layui.form;

        //加载列表的后端 url
        var getListUrl = '/commodity/detail/list';
        //对于任意一个 table，按照官方的说法，有三种不同的初始化渲染方式，不多介绍，而这里使用的方式姑且看做第三种：转换静态表格 方式
        //转换静态表格方式，自然首先需要有一个已经存在的表格，然后再通过 js 方式转化为 Layui 表格
        //无论哪种方式的 Layui table 初始化自然需要配置项
        //通过转化的方式初始化 Layui table，配置项部分可以在 源table中，部分在js中，源 table 的源代码上文已经给出，下面给出一个示例的 js 中的配置项
        var tableOptions = {
            elem: '#EditListTable',
            url: getListUrl, //请求地址
            method: 'GET', //方式
            id: 'EditListTable', //生成 Layui table 的标识 id，必须提供，用于后文刷新操作，笔者该处出过问题
            page: true, //是否分页
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            where: { customerId: customerId }, //请求后端接口的条件，该处就是条件错误点，按照官方给出的代码示例，原先写成了 where: { key : { type: "all" } }，结果并不是我想的那样，如此写，key 将是后端的一个类作为参数，里面有 type 属性，如果误以为 key 是 Layui 提供的格式，那就大错特错了
            response: { //定义后端 json 格式，详细参见官方文档
                statusName: 'code', //状态字段名称
                statusCode: '200', //状态字段成功值
                msgName: 'msg', //消息字段
                countName: 'total', //总数字段
                dataName: 'rows' //数据字段
            },
            limit: 10,//每页显示条数
            limits: [10,20,50,100,150,200,300],//可选择范围
            defaultToolbar: ['filter'],
            toolbar: '#toolbar'
        };
        // 表初始化
        var createTable = function () {
            table.init('EditListTable', tableOptions);// table lay-filter
        };
        // 表刷新方法
        var reloadTable = function () {
            table.reload("tableid", { //此处是上文提到的 初始化标识id
                url: getListUrl,
                where: {customerId: customerId}
            });
        };
        // 表初始化
        createTable();

        //头部工具栏按钮触发事件
        table.on('toolbar(EditListTable)', function(obj){
            //获取选中行
            let toolbar = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    files = [];
                    $("#file_content").html("");
                    $("#original_img").remove();
                    //先清空表单数据
                    $("#add_shop_form")[0].reset();
                    form.render();
                    layer.open({
                        type: 1
                        ,title: '添加商品'
                        , content: $('#add_shop_model')
                        , area: 'auto'//定义宽和高
                        , btnAlign: 'c' //按钮居中
                        , shade: 0 //不显示遮罩
                        ,btn: ['确定', '取消']
                        , yes: function () {
                            //上传图片到存储桶
                            let backUrls = uploadCOS(files);
                            let shop_obj = $("#add_shop_form").serializeObject();
                            shop_obj.customerId = customerId;
                            if(!isNotNull(shop_obj.commodityMap)){
                                shop_obj.commodityMap = backUrls;
                            }
                            $.ajax({
                                type:'post',
                                url:'/commodity/detail/add',
                                data:JSON.stringify(shop_obj),
                                dataType:'json',
                                contentType: 'application/json; charset=UTF-8',
                                success:function(req){
                                    layui.use('layer', function(){
                                        $("#add_shop_model").css("display","none");
                                        var layer = layui.layer;
                                        layer.msg("已添加！");
                                        setTimeout(function(){
                                            layer.closeAll();
                                        }, 2000);
                                    });
                                    // 重载表格数据
                                    reloadTable();
                                    return false;
                                },
                                error:function(e){
                                    layui.use('layer', function(){
                                        $("#add_shop_model").css("display","none");
                                        var layer = layui.layer;
                                        layer.msg("出错啦！");
                                        setTimeout(function(){
                                            layer.closeAll();
                                        }, 2000);
                                    });
                                }
                            })
                        }
                        ,btn2: function(index, layero){
                            //按钮【按钮二】的回调
                            layer.closeAll();
                            $("#add_shop_model").css("display","none");
                            //return false 开启该代码可禁止点击该按钮关闭
                        }
                        ,cancel: function(){
                            //右上角关闭回调
                            layer.closeAll();
                            $("#add_shop_model").css("display","none");
                            //return false 开启该代码可禁止点击该按钮关闭
                        }
                    });
                    break;
                case 'edit':
                    if(toolbar.data.length > 0){
                        if(toolbar.data.length > 1){
                            layer.msg("只能选择一项进行编辑噢！");
                        }else{
                            $.ajax({
                                type:'GET',
                                url:'/commodity/'+toolbar.data[0].commodityId,
                                dataType:'json',
                                contentType: 'application/json; charset=UTF-8',
                                success:function(res){
                                    let original_commodity = res.data
                                    //给弹出的表单赋值
                                    form.val("addShopForm", {
                                        "commodityName": original_commodity.commodityName
                                        ,"commodityMap": original_commodity.commodityMap
                                        ,"commodityLink": original_commodity.commodityLink
                                        ,"specification": original_commodity.specification
                                        ,"supplyPrice": original_commodity.supplyPrice
                                        ,"floorPrice": original_commodity.floorPrice
                                        ,"dropShipping": original_commodity.dropShipping
                                        ,"fare": original_commodity.fare
                                        ,"remark": original_commodity.remark
                                    });
                                    //初始化图片
                                    $("#original_img").remove();
                                    if(isNotNull(original_commodity.commodityMap)){
                                        $("#imgSelector").before("<div id='original_img' style='padding-bottom: 10px;'><img src='"+original_commodity.commodityMap+"' width='100px' height='100px' /></div>");
                                    }
                                    layer.open({
                                        type: 1
                                        ,title: '修改商品'
                                        , content: $('#add_shop_model')
                                        , area: 'auto'//定义宽和高
                                        , btnAlign: 'c' //按钮居中
                                        , shade: 0 //不显示遮罩
                                        ,btn: ['确定', '取消']
                                        , yes: function (index, layero) {
                                            let shop_obj = $("#add_shop_form").serializeObject();
                                            original_commodity.commodityName = shop_obj.commodityName
                                            original_commodity.commodityLink = shop_obj.commodityLink
                                            original_commodity.specification = shop_obj.specification
                                            original_commodity.supplyPrice = shop_obj.supplyPrice
                                            original_commodity.floorPrice = shop_obj.floorPrice
                                            original_commodity.dropShipping = $('input[name="dropShipping"]:checked').val()
                                            original_commodity.fare = shop_obj.fare
                                            original_commodity.remark = shop_obj.remark
                                            if(isNotNull(shop_obj.commodityMap)){
                                                original_commodity.commodityMap = shop_obj.commodityMap;
                                            }else{
                                                //上传图片到存储桶
                                                let backUrls = uploadCOS(files);
                                                if(isNotNull(backUrls)){
                                                    original_commodity.commodityMap = backUrls;
                                                }
                                            }
                                            $.ajax({
                                                type:'PUT',
                                                url:'/commodity/detail/edit',
                                                data:JSON.stringify(original_commodity),
                                                dataType:'json',
                                                contentType: 'application/json; charset=UTF-8',
                                                success:function(req){
                                                    $("#add_shop_model").css("display","none");
                                                    layer.close(index);
                                                    layer.msg("修改成功！");
                                                    // 重载表格数据
                                                    setTimeout(function(){
                                                        reloadTable();
                                                    }, 1500);
                                                    return false;
                                                },
                                                error:function(e){
                                                    $("#add_shop_model").css("display","none");
                                                    layer.close(index);
                                                    layer.msg("出错啦！");
                                                }
                                            })
                                            //上传图片到存储桶

                                        }
                                        ,btn2: function(index, layero){
                                            //按钮【按钮二】的回调
                                            layer.closeAll();
                                            $("#add_shop_model").css("display","none");
                                            //return false 开启该代码可禁止点击该按钮关闭
                                        }
                                        ,cancel: function(){
                                            //右上角关闭回调
                                            layer.closeAll();
                                            $("#add_shop_model").css("display","none");
                                            //return false 开启该代码可禁止点击该按钮关闭
                                        }
                                    });
                                    return false;
                                },
                                error:function(e){
                                    layer.msg("出错啦！");
                                }
                            })
                        }
                    }else{
                        layer.msg("请选择至少一项！");
                    }
                    break;
                case 'delete':
                    if(toolbar.data.length > 0) {
                        let ids = []
                        for(let i=0; i<toolbar.data.length; i++){
                            ids.push(toolbar.data[i].commodityId);
                        }
                        $.ajax({
                            type:'DELETE',
                            url:'/commodity/detail/delete',
                            data:JSON.stringify(ids),
                            dataType:'json',
                            contentType: 'application/json; charset=UTF-8',
                            success:function(req){
                                $("#add_shop_model").css("display","none");
                                layer.msg("已删除！");
                                // 重载表格数据
                                reloadTable();
                                return false;
                            },
                            error:function(e){
                                $("#add_shop_model").css("display","none");
                                layer.msg("出错啦！");
                            }
                        })
                    }else{
                        layer.msg("请至少选择一项");
                    }
            };
        });

    });

    //搜索
    function search(){
        layui.use(['table', 'layer'], function () {//layui 模块引用，根据需要自行修改
            let layer = layui.layer, table = layui.table;
            table.reload('tableid', {
                where: {
                    searchStr:$("#keyword").val()
                }
                ,page: {
                    pageNum: 1 //重新从第 1 页开始
                }
            });
        })
    }

    //回车搜索
    function keydownSearch() {
        let event = window.event || arguments.callee.caller.arguments[0];
        if (event.keyCode == 13)
        {
            search();
        }
    }

    //渲染日期控件
    layui.use('laydate', function(){
        let laydate = layui.laydate;
        laydate.render({
            elem: '#startDateid',
            trigger: 'click'
        });
    });

    layui.use('laydate', function(){
        let laydate = layui.laydate;
        laydate.render({
            elem: '#dueDateid',
            trigger: 'click'
        });
    });

    //文件上传
    layui.use('upload', function(){
        let upload = layui.upload;
        //执行实例
        let uploadInst = upload.render({
            elem: '#UploadData' //绑定元素
            ,url: '' //上传接口
            ,accept: 'images' //允许上传的文件类型
            ,auto: false //选择文件后不自动上传
            ,choose: function(obj){
                //将每次选择的文件追加到文件队列
                // files = obj.pushFile();
                //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                obj.preview(function(index, file, result){
                    // console.log(index); //得到文件索引
                    // console.log(file); //得到文件对象
                    // console.log(result); //得到文件base64编码，比如图片
                    let File = {fileInfo:file,data:result}
                    files.push(File)
                    //obj.resetFile(index, file, '123.jpg'); //重命名文件名，layui 2.3.0 开始新增

                    //这里还可以做一些 append 文件列表 DOM 的操作
                    let arr_index = files.length-1
                    $("#file_content").append("<p style='color: #1ea0fa;padding-bottom: 3px;' id='file_list"+arr_index+"'><span style='padding-right: 5px;font-size: 16px;'>"+file.name+"</span><span style='padding-top: 2px;font-weight: 600;vertical-align: middle;'><i class='layui-icon' onclick='del_file("+arr_index+")'>&#x1006;</i></span></p>")
                    //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
                    //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
                });
            }
        });
    });

    //删除需要上传的文件
    function del_file(index){
        files.splice(index, 1);
        $("#file_list"+index).remove();
    }

    //获取地址栏参数
    function GetQueryString(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]);
        return null;
    }

    /**
     * 判断值是否不为空
     * @param {Object} val
     */
    function isNotNull(val){
        if(val!=='undefined' && val!=="" && val!=null){
            return true
        }
        return false
    }

    //添加商品图片上传
    $("#imgSelector").change(function () {
        $("#original_img").remove();
        files = $("#imgSelector")[0].files;
    });

    //授权申请附件上传
    $("#fileSelector").change(function () {
        let file = $("#fileSelector")[0].files;
        let url = uploadCOS(file);
        if(isNotNull(url)){
            attachments.push(url);//上传完毕添加到attachments中
            randerAttachList(1);//重新渲染附件列表
        }
    });

    //渲染附件列表：0为展示列表，1为可删除列表
    function randerAttachList(flag){
        $("#attachment_content").html("");//先清空附件列表显示
        for(let i in attachments){
            let attach = attachments[i];
            let filename = attach.substring(attach.lastIndexOf("/")+1);
            if(flag == 0){
                $("#attachment_content").append("<p style='color: #1ea0fa;padding-bottom: 3px;' id='attachment_list"+i+"'><a href='"+attach+"' target='_blank'>"+filename+"</a></p>")
            }else if(flag == 1){
                $("#attachment_content").append("<p style='color: #1ea0fa;padding-bottom: 3px;' id='attachment_list"+i+"'><a href='"+attach+"' target='_blank'>"+filename+"</a><span style='padding-top: 2px;font-weight: 600;vertical-align: middle;color: red;padding-left: 3px;'><i class='layui-icon' onclick='del_attchment("+i+")'>&#x1006;</i></span></p>")
            }
        }
    }

    //删除文件
    function del_attchment(index){
        attachments.splice(index, 1);
        $("#attachment_list"+index).remove();
    }

    //授权申请表单提交
    layui.use('form', function(){
        var form = layui.form;
        form.on('submit(submitAuthForm)',function (res) {
            let OriginalAtuhData ={}
            $.ajax({
                url: '/supplement/'+customerId,
                type: 'get',
                data: {},
                dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系！！！
                success: function (res) {
                    if(res.data){
                        OriginalAtuhData = res.data;
                    }
                    OriginalAtuhData.customerId = customerId
                    OriginalAtuhData.shopName = $('input[name="shopName"]').val()
                    OriginalAtuhData.oneClickDelivery = $('input[name="oneClickDelivery"]:checked').val()
                    OriginalAtuhData.splitAccounts = $("input[name='splitAccounts']:checked").val()
                    OriginalAtuhData.taobaoDistribution = $("input[name='taobaoDistribution']:checked").val()
                    OriginalAtuhData.communityDistribution = $("input[name='communityDistribution']:checked").val()
                    OriginalAtuhData.otherDistribution = $('input[name="otherDistribution"]').val()
                    OriginalAtuhData.startDate = $('input[name="startDate"]').val()
                    OriginalAtuhData.dueDate = $('input[name="dueDate"]').val()
                    //保存附件链接
                    if(attachments.length > 0){
                        let backUrls = "";
                        for (let i in attachments){
                            if(backUrls == ""){
                                backUrls = attachments[i];
                            }else{
                                backUrls += "," + attachments[i];
                            }
                        }
                        OriginalAtuhData.attachment = backUrls;
                    }
                    //保存客户跟进记录
                    let originalLog = $("#logData").val();
                    let customerLogId = customerId;
                    let needAddFlag = true;
                    $.each(logDataJson,function(i,item){
                        if(item.edit){
                            item.content = originalLog;
                            needAddFlag = false;
                        }
                        item.customerLogId = item.customerLogId.toString()
                    });
                    if(needAddFlag){
                        logDataJson = [{customerLogId:customerLogId,content:originalLog.toString(),edit:"true"}];
                    }
                    let params = {"supplement": OriginalAtuhData,"logData": logDataJson}
                    $.ajax({
                        type:"POST",
                        url:'/supplement/save',
                        data:JSON.stringify(params),
                        dataType:'json',
                        contentType: 'application/json; charset=UTF-8',
                        success:function(req){
                            layui.use('layer', function(){
                                var layer = layui.layer;
                                if(isNotNull(OriginalAtuhData.supplementId)){//编辑
                                    layer.msg("更新成功！");
                                }else{//新增
                                    layer.msg("新增成功！");
                                }
                            });
                            //按钮变为编辑，并且给输入框加上disabled属性
                            randerAttachList(0);
                            $("#fileSelector").attr("hidden","hidden");
                            $("#auth_form_id *").attr("disabled","disabled");
                            $("#EditFormBtn").removeAttr('disabled');
                            $("#SubmitBtn").hide();
                            $("#EditFormBtn").show();
                            form.render();
                            return false;
                        },
                        error:function(e){
                            layui.use('layer', function(){
                                var layer = layui.layer;
                                if(isNotNull(OriginalAtuhData.supplementId)){//编辑
                                    layer.msg("更新失败！");
                                }else{//新增
                                    layer.msg("新增失败！");
                                }
                            });
                        }
                    })
                }
            });
            return false;
        })
    });

    // 将表单数据序列化为一个json对象，例如 {"name":"zs", "age":10}
    // 使用：var jsonObj = $("#formId").serializeObject();
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    //编辑授权申请
    function editAuthForm(){
        layui.use('form', function() {
            let form = layui.form;
            $("#auth_form_id *").removeAttr('disabled');
            $("#fileSelector").removeAttr("hidden");
            randerAttachList(1);
            $("#EditFormBtn").hide();
            $("#SubmitBtn").show();
            form.render();
        })
    }

    //上传文件到存储桶
    function uploadCOS(file_arr) {
        let backUrls = "";
        //上传图片到存储桶
        for (let i in file_arr){
            let fileName = file_arr[i].name
            cos.putObject({
                Bucket: Bucket, /* 必须 */
                Region: Region,     /* 存储桶所在地域，必须字段 */
                Key:  folderName + "/" + fileName,/*文件夹+文件名称 必须 */
                Body: file_arr[i], // 上传文件对象
                onProgress: function(progressData) {
                    console.log(JSON.stringify(progressData));
                    let backUrl = "https://" + Bucket + ".cos."+ Region + ".myqcloud.com/" + folderName + "/" + fileName;
                    if(backUrls == ""){
                        backUrls = backUrl;
                    }else{
                        backUrls += "," + backUrl;
                    }
                    return backUrls;
                }
            }, function(err, data) {
                console.log(err || data);
                // if(data){
                //     let backUrl = "https://" + Bucket + ".cos."+ Region + ".myqcloud.com/" + folderName + "/" + fileName;
                //     if(backUrls == ""){
                //         backUrls = backUrl;
                //     }else{
                //         backUrls += "," + backUrl;
                //     }
                // }
            });
        }
        return backUrls;
    }

</script>

</html>